package cn.zb.config.security;

import cn.zb.entity.auth.SysUser;
import cn.zb.common.util.Result;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Security 从请求头中获取token验证过滤器
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头获取token
        String token = request.getHeader("token");
        // 如果没有token 直接放行
        if(StringUtils.isBlank(token) || request.getRequestURI().endsWith("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        // 如果有token 就从redis取出
        SysUser user = (SysUser) redisTemplate.opsForValue().get("login:"+token);
        if(user == null){
            response.setContentType("application/json;charset=utf-8");
            Result fail = Result.fail(401, "您的会话已丢失,请重新登录");

            response.getWriter().print(JSON.toJSONString(fail));
            return;
        }
        // 每次请求重置会话时间30min
        redisTemplate.expire("login:"+token,30, TimeUnit.MINUTES);
        //将用户信息存放在SecurityContextHolder.getContext()，后面的过滤器就可以获得用户信息了。
        UsernamePasswordAuthenticationToken upat=
                new UsernamePasswordAuthenticationToken(user.getUsername(),null,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(upat);
        filterChain.doFilter(request,response);
    }
}
